package cn.iocoder.yudao.framework.web.servlet;

import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.web.core.handler.GlobalExceptionHandler;
import jakarta.annotation.Nonnull;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.servlet.HandlerInterceptor;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 *  管理后台默认密码拦截器（开启了强制修改默认密码，若未改密则报错提示）
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/04/13
 */
@Slf4j
public class AdminPasswordInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object object) {
        String uri = request.getRequestURI();
        if (!uri.startsWith("/admin-api/")) {
            return true;
        }
        if (uri.startsWith("/admin-api/infrastructure/auth/") ||
            uri.startsWith("/admin-api/infrastructure/user/") ||
            uri.startsWith("/admin-api/infrastructure/tenant/")) {
            return true;
        }
        Long userId = getLoginUserId();
        if (userId == null || userId <= 0) {
            return true;
        }
        // TODO 检查默认密码是否修改
        if (false) {
            responseJson(request, response, "为了安全考虑，请先修改默认密码");
            return false;
        }
        return true;
    }

    private void responseJson(HttpServletRequest request, HttpServletResponse response, String msg) {
        GlobalExceptionHandler globalExceptionHandler = SpringUtil.getBean(GlobalExceptionHandler.class);
        CommonResult<?> result = globalExceptionHandler.accessDeniedExceptionHandler(request, new AccessDeniedException(msg));
        JakartaServletUtil.write(response, JsonUtils.toJsonString(result), "application/json; charset=utf-8");
    }

}

